package com.weixin.project.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weixin.project.Entity.Notice;
import com.weixin.project.Service.NoticeService;
import com.weixin.project.Util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class NoticeController {
    @Value("${logging.pattern.dateformat}")
    String dateFormat;
    @Autowired
    NoticeService noticeService;
    @PostMapping("/notice/create_notice")
    JSONObject addNotice(@RequestBody JSONObject params){
        Notice notice = new Notice();
        notice.setCreateTime(new Date());
        notice.setSrc(params.getString("src"));
        notice.setText(params.getString("text"));
        notice.setTitle(params.getString("title"));
        noticeService.storeNotice(notice);
        return ResponseUtil.success();
    }

    @GetMapping("/notice/get_notice_detail")
    JSONObject getNoticeDetail(@RequestParam("id") Integer noticeId){
        Notice notice = noticeService.findNotice(noticeId);
        JSONObject ret = new JSONObject();
        ret.put("title", notice.getTitle());
        ret.put("id", notice.getId());
        ret.put("text", notice.getText());
        ret.put("time", new SimpleDateFormat(dateFormat).format(notice.getCreateTime()));
        return ResponseUtil.success("", ret);
    }

    @GetMapping("/notice/get_notice_list")
    JSONObject getNoticeList(@RequestParam("page") Integer page){
        page--;
        Page<Notice> noticePage = noticeService.findNotices(page);
        List<Notice> notices = noticePage.getContent();
        JSONArray noticeList = new JSONArray();
        for (Notice notice:notices){
            JSONObject noticeObj = new JSONObject();
            noticeObj.put("id", notice.getId());
            noticeObj.put("src", notice.getSrc());
            noticeObj.put("title", notice.getTitle());
            noticeObj.put("time", new SimpleDateFormat(dateFormat).format(notice.getCreateTime()));
            noticeList.add(noticeObj);
        }
        JSONObject ret = new JSONObject();
        ret.put("notice", noticeList);
        ret.put("all_pages", noticePage.getTotalPages());
        return ResponseUtil.success("", ret);
    }
}
